<template>
  <!-- 搜 索工作栏 -->
  <ContentWrap>
    <el-form class="-mb-15px" :model="form" ref="queryFormRef" :inline="true" label-width="68px">
      <el-form-item>
        <el-button type="primary" plain @click="openForm('create', null, null)">
          <Icon icon="ep:plus" class="mr-5px" /> 新 增
        </el-button>
        <el-button type="danger" plain @click="toggleExpandAll">
          <Icon icon="ep:sort" class="mr-5px" /> 展开/折叠
        </el-button>
      </el-form-item>
      <el-form-item>
        <el-tooltip
          placement="top-start"
          content='表格上方输入框为查询输入框，可在里面输入搜索关键字字符串，鼠标焦点移出输入框后进行搜索操作，表格中将显示查询结果，搜索关键字字符串为模糊查询。如有多个搜索内容，可以空格进行分隔。第二种搜索方式为"复杂搜索"，点击"复杂搜索"按钮后，可以设置多条件复杂搜索。第三种搜索方式为“筛选”，表格中表头列中如果有“下拉”标志按钮，则可以点击，弹出下拉复选框，选择后，点击下拉复选框中“筛选”文字，则可以进行数据的筛选操作，可快速查找到自己想看的数据，筛选结果将显示在表格中。表格中表头列中如果有“上下”标志按钮，则可以点击上按钮或下按钮进行排序，可快速查找或对比数据。排序结果不是针对于分页列表中本页内容，而是针对于分页列表中所有内容。本模块暂不支持多列依序排列，只支持针对于某一列的排序，所以点击排序按钮后，以前的排序结果将无效。排序结果只针对于本次数据浏览，不会影响到数据库的实际结果。当页面刷新后，排序需重新进行。'
        >
          <el-button
            type="primary"
            plain
            :disabled="queryBuilderShow"
            @click="queryBuilderShow = true"
          >
            复杂搜索
          </el-button>
        </el-tooltip>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <ContentWrap v-if="queryBuilderShow">
    <el-row
      ><el-col :span="16">
        <tiny-query-builder
          ref="queryBuilder"
          :config="config"
          :query="query"
          :on-query-change="queryChange" /></el-col
      ><el-col :span="8">
        <el-button type="primary" plain @click="handleQuery"> 搜 索 </el-button>
        <el-button type="primary" plain @click="queryBuilderShowFalse">
          清除搜索条件后隐藏
        </el-button></el-col
      ></el-row
    >
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      v-loading="loading"
      :data="list"
      row-key="id"
      :default-expand-all="isExpandAll"
      v-if="refreshTable"
    >
      <el-table-column sortable="true" prop="name" label="部门名称" width="260" />
      <el-table-column label="操 作" align="center" class-name="fixed-width">
        <template #default="scope">
          <el-button link type="primary" @click="openForm('create', null, scope.row.id)">
            新增子部门
          </el-button>
          <el-button link type="primary" @click="openForm(scope.row.id, null)"> 修 改 </el-button>
          <el-button link type="danger" @click="handleDel(scope.row.id)"> 删 除 </el-button>
        </template>
      </el-table-column>
    </el-table>
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <update ref="formRef" @success="getPage" />
</template>
<script setup lang="ts" name="SystemDept">
import { QueryBuilder as TinyQueryBuilder } from '@opentiny/vue'
import { handleTree } from '@/utils/tree'
import * as Api from '@/api/userCenter/dept/dept'
import update from './update.vue'
import * as StaffApi from '@/api/userCenter/dept/staff'

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const queryBuilderShow = ref(false)

const queryBuilder = ref()

import { operators, defaultOptions } from '@/utils/queryBuilder'

const config = {
  operators,
  ...defaultOptions,
  combinators: [
    {
      name: 'and',
      label: '且'
    },
    {
      name: 'or',
      label: '或'
    }
  ],
  fields: [
    {
      name: 'name',
      label: '名 称'
    }
  ]
}

import { uuid } from '@/utils'

const query = ref({
  id: uuid(),
  combinator: 'and',
  not: false,
  rules: []
})

const queryChange = async (data) => {
  query.value = data
}

const queryBuilderShowFalse = async () => {
  query.value = {
    id: uuid(),
    combinator: 'and',
    not: false,
    rules: []
  }
  queryBuilderShow.value = false
}

const loading = ref(false) // 列表的加载中
const list = ref() // 列表的数据
const form = ref({
  query: '',
  title: '',
  name: undefined,
  status: undefined,
  pageNum: 1,
  pageSize: 100,
  sortName: 'order_num', // 排序,字段
  sortOrder: 'DESC' // 排序,asc／desc
})
let filterArrLet: any[] = []

const queryFormRef = ref() // 搜 索的表单
const isExpandAll = ref(true) // 是否展开,默认全部展开
const refreshTable = ref(true) // 重新渲染表格状态
const userList = ref<StaffApi.UserVO[]>([]) // 用户列表

/** 查询部门列表 */
const getPage = async () => {
  loading.value = true
  try {
    const data = await Api.getPage(form.value)
    console.log(data)
    list.value = handleTree(data)
  } catch (t) {
    console.log(t)
    loading.value = false
    message.error('查询列表失败')
  } finally {
    loading.value = false
  }
}

/** 展开/折叠操作 */
const toggleExpandAll = () => {
  refreshTable.value = false
  isExpandAll.value = !isExpandAll.value
  nextTick(() => {
    refreshTable.value = true
  })
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: string, parentId?: string) => {
  if (!id) {
    id = uuid()
  }
  formRef.value.open(type, id, parentId)
}

/** 删除按钮操作 */
const handleDel = async (id: string) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await Api.del(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getPage()
  } catch {}
}

const sortChange = async (data) => {
  form.value.sortOrder = data.order.replace(/ending$/, '')
  form.value.sortName = data.prop

  getPage()
}

const filterChange = async (filters) => {
  filterArrLet.push(filters)
  form.value.filters = encodeURIComponent(JSON.stringify(filterArrLet))

  getPage()
}

/** 初始化 **/
onMounted(async () => {
  await getPage()
  // 获取用户列表
  userList.value = await StaffApi.getSimpleUserList()
})
</script>
